package com.mjlf.mqzook.schedule;

import com.mjlf.mqzook.config.ZkConfig;
import com.mjlf.mqzook.entity.RegistryServer;
import com.mjlf.mqzook.inter.RegistryFacotry;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.Iterator;
import java.util.Set;

/**
 * @ClassName ServerClear
 * @Author mjlft
 * @Date 2020/2/18 13:48
 * @Version 1.0
 * @Description TODO
 */
@Component
public class ServerClear {
    Logger logger = LoggerFactory.getLogger(ServerClear.class);

    //多长时间没有更新就执行删除
    @Value("${server.delete}")
    private long timeDelete;

    @Scheduled(cron = "${server.corn}")
    public void delete(){
        Iterator<String> iterator = RegistryFacotry.servers.keySet().iterator();
        while (iterator.hasNext()){
            String name = iterator.next();
            Set<RegistryServer> registryServers = RegistryFacotry.servers.get(name);
            if(registryServers == null || registryServers.isEmpty()){
                RegistryFacotry.servers.remove(name);
            }
            for(RegistryServer registryServer : registryServers){
                if(registryServer.getUpdateTime() < System.currentTimeMillis() - timeDelete){
                    registryServers.remove(registryServer);
                    logger.info("清除服务{}:{}", registryServer.getHost(), registryServer.getPort());
                }
            }
        }
    }
}
